package xyz.jcat.web.security;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import xyz.jcat.auth.token.AccessTokenUtils;
import xyz.jcat.auth.token.UserTokenDto;
import xyz.jcat.common.auth.UserContextHolder;
import xyz.jcat.common.util.StringUtils;
import xyz.jcat.security.UserRoleAuthenticationToken;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

public class HttpHeaderAccessTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String requestHeaderToken = request.getHeader(AccessTokenUtils.TOKEN_HEADER);
        String token = AccessTokenUtils.getHeaderAccessToken(requestHeaderToken);
        if(StringUtils.isNotEmpty(token)) {
            UserTokenDto userToken = AccessTokenUtils.getUserToken(token);
            if(!Objects.isNull(userToken)) {
                UserRoleAuthenticationToken authenticationToken =
                        new UserRoleAuthenticationToken(userToken.getId(), userToken.getRoles());
                authenticationToken.setAuthenticated(true);
                //授权
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                //
                UserContextHolder.getInstance().setUserId(authenticationToken.getUserId());
            }
        }
        filterChain.doFilter(request, response);
        UserContextHolder.getInstance().clear();
    }

}
